﻿using System;
using System.Linq;
using System.Web.Mvc;
using FinancePortal.Business.Infraestructure;
using FinancePortal.Business.Repository;
using FinancePortal.Web.Model;
using FinancePortal.Web.Models;
using System.Collections.Generic;

namespace FinancePortal.Web.Controllers
{
    [Permission(Roles = "Worker, Administrator")]
    public class AreaController : Controller
    {
        private readonly IAreaRepository _areaRepository;
        private readonly IResourceRepository _resourceRepository;

        public AreaController(IAreaRepository areaRepository, IResourceRepository resourceRepository)
        {
            _areaRepository = areaRepository;
            _resourceRepository = resourceRepository;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AreaList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                //var ids = ResourceManagement.GetAreas(HttpContext);

                //var idArea = _resourceRepository.GetBySOEID(ResourceManagement.GetSOEID(this.Request)).AreaId;
                var areas = _areaRepository.GetAll() // GetByResource(idArea)
                    .OrderBy(jtSorting)
                    .Skip(jtStartIndex)
                    .Take(jtPageSize)
                    .ToList();
                    
                var areasList = areas.Select(m =>
                    new AreaViewModel
                    {
                        Id = m.Id,
                        Name = m.Name,
                        ParentAreaId = m.ParentAreaId
                    });

                return Json(new 
                { 
                    Result = "OK",
                    Records = areasList,
                    TotalRecordCount = _areaRepository.GetAll().Count() 
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult GetParent()
        {
            try
            {
                //var ids = ResourceManagement.GetAreas(HttpContext);
                var listArea = _areaRepository.GetAll().Select(a =>
                    new 
                    {
                        DisplayText = a.Name,
                        Value = a.Id
                    }).ToList();

                listArea.Insert(0, new
                {
                    DisplayText = "",
                    Value = 0
                });

                return Json(new
                {
                    Result = "OK",
                    Options = listArea
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        [Transactional]
        [Permission(Roles="Administrator")]
        public JsonResult CreateArea(AreaViewModel view)
        {
            try 
            { 
                if (!ModelState.IsValid) 
                { 
                    return Json(new 
                    { 
                        Result = "ERROR", 
                        Message = "Form is not valid! Please correct it and try again." 
                    }); 
                } 
                
                //_areaRepository.Save(AreaViewModel.ToModel(view)); 

                var model = AreaViewModel.ToModel(view);
                _areaRepository.Save(model);
                view.Id = model.Id;
                
                return Json(new 
                {
                    Result = "OK",
                    Record = view 
                }); 
            }
            catch (Exception ex) 
            { 
                return Json(new { Result = "ERROR", Message = ex.Message }); 
            }
        }

        [HttpPost]
        [Transactional]
        [Permission(Roles="Administrator")]
        public JsonResult UpdateArea(AreaViewModel view)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! Please correct it and try again."
                    });
                }

                _areaRepository.Save(AreaViewModel.ToModel(view));

                return Json(new
                {
                    Result = "OK"
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        [Transactional]
        [Permission(Roles = "Administrator")]
        public JsonResult DeleteArea(int id)
        {
            try 
            {
                var model = _areaRepository.GetById(id);
                _areaRepository.Delete(model); 
                
                return Json(new 
                { 
                    Result = "OK" 
                }); 
            }
            catch (Exception ex) 
            { 
                return Json(new { Result = "ERROR", Message = ex.Message }); 
            } 
        }

        #region Old Actions
        /*
        public ActionResult Index()
        {
            var ids = ResourceManagement.GetAreas(HttpContext);
            var list = _areaRepository.GetByResource(ids);
            return View(list);
        }

        [Permission(Roles = "Administrator")]
        public ActionResult Create()
        {
            LoadDropDown();

            return View();
        }

        [HttpPost, Transactional, Permission(Roles = "Administrator")]
        public ActionResult Create(Area area)
        {
            if (ModelState.IsValid)
            {
                _areaRepository.Save(area);
                return RedirectToAction("Index");
            }

            LoadDropDown();

            return View(area);
        }

        private void LoadDropDown()
        {
            var ids = ResourceManagement.GetAreas(HttpContext);
            var listArea = _areaRepository.GetByResource(ids);
            ViewBag.Area = new SelectList(listArea, "Id", "Name");
        }

        [Permission(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            var area = _areaRepository.GetById(id);

            LoadDropDown();

            return View(area);
        }

        [HttpPost, Transactional, Permission(Roles = "Administrator")]
        public ActionResult Edit(Area area)
        {
            if (ModelState.IsValid)
            {
                _areaRepository.Save(area);
                return RedirectToAction("Index");
            }

            LoadDropDown();

            return View(area);
        }

        [Transactional, Permission(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            var area = _areaRepository.GetById(id);
            _areaRepository.Delete(area);

            return RedirectToAction("Index");
        }
        */

        #endregion
    }
}
